<template>
  <view class="doctors-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <uni-icons type="left" size="20" color="#333"></uni-icons>
      </view>
      <text class="header-title">{{ departmentName }}医生</text>
      <view class="placeholder"></view>
    </view>

    <!-- 排序栏：综合 / 好评 / 咨询数 / 价格（默认隐藏） -->
    <view class="sort-bar" v-if="showSortBar">
      <view class="sort-item" :class="{ active: sortKey === 'comprehensive' }" @click="changeSort('comprehensive')">综合</view>
      <view class="sort-item" :class="{ active: sortKey === 'praise' }" @click="changeSort('praise')">好评</view>
      <view class="sort-item" :class="{ active: sortKey === 'service' }" @click="changeSort('service')">咨询数</view>
      <view class="sort-item" :class="{ active: sortKey === 'price' }" @click="togglePriceSort()">价格<text class="arrow">{{ sortKey === 'price' ? (sortOrder === 'asc' ? '↑' : '↓') : '' }}</text></view>
    </view>
    
    <!-- 科室标签 -->
    <view class="department-tabs">
      <view 
        class="tab-item" 
        :class="{ active: activeDepartment === item.key }"
        v-for="item in departments" 
        :key="item.key"
        @click="switchDepartment(item.key)"
      >
        <text>{{ item.name }}</text>
      </view>
    </view>
    
    <!-- 医生列表 -->
    <view class="doctors-list">
      <view 
        class="doctor-card" 
        v-for="doctor in sortedDoctors" 
        :key="doctor.id"
        @click="viewDoctorDetail(doctor)"
      >
        <view class="doctor-avatar">
          <image :src="doctor.avatar" mode="aspectFill"></image>
          <view class="online-status" :class="{ online: doctor.isOnline }"></view>
        </view>
        <view class="doctor-info">
          <view class="doctor-name">{{ doctor.name }}</view>
          <view class="doctor-meta">
            <text class="role" v-if="doctor.title">{{ doctor.title }}</text>
            <text class="divider" v-if="doctor.title && doctor.hospital">｜</text>
            <text class="hospital" v-if="doctor.hospital">{{ doctor.hospital }}</text>
          </view>
          <view class="doctor-specialty" v-if="doctor.specialty">擅长：{{ doctor.specialty }}</view>
          <view class="doctor-stats">
            <text class="consultation-count">服务患者数 {{ doctor.consultationCount }}</text>
            <text class="rating">好评率 {{ doctor.rating }}%</text>
          </view>
        </view>
        <view class="consultation-btn">
          <text class="btn-text">{{ doctor.isOnline ? '立即咨询' : '预约咨询' }}</text>
          <text class="price">{{ doctor.price }}币/次</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getDoctorsByDeptId } from '@/api/doctor'
import { getDepartmentList } from '@/api/department'
import config from '@/config.js'
export default {
  data() {
    return {
      activeDepartment: 'internal',
      departmentName: '内科',
      deptId: null,
      doctorsList: [],
      // 顶部科室标签（优先从后端加载）
      departments: [],
      // 排序
      sortKey: 'comprehensive', // comprehensive | praise | service | price
      sortOrder: 'desc', // price 支持 asc/desc
      showSortBar: false,
      doctorsData: {
        internal: [
          {
            id: 1,
            name: '张医生',
            title: '主任医师',
            hospital: '北京协和医院',
            specialty: '心血管疾病、高血压、糖尿病',
            avatar: 'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1111111111,1111111111&fm=26&gp=0.jpg',
            isOnline: true,
            consultationCount: 1256,
            rating: 98,
            price: 50
          },
          {
            id: 2,
            name: '李医生',
            title: '副主任医师',
            hospital: '北京大学第一医院',
            specialty: '呼吸系统疾病、肺炎、哮喘',
            avatar: 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2222222222,2222222222&fm=26&gp=0.jpg',
            isOnline: false,
            consultationCount: 892,
            rating: 96,
            price: 40
          }
        ],
        ophthalmology: [
          {
            id: 3,
            name: '王医生',
            title: '主任医师',
            hospital: '北京同仁医院',
            specialty: '白内障、青光眼、近视手术',
            avatar: 'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3333333333,3333333333&fm=26&gp=0.jpg',
            isOnline: true,
            consultationCount: 756,
            rating: 99,
            price: 60
          }
        ],
        orthopedics: [
          {
            id: 4,
            name: '赵医生',
            title: '主任医师',
            hospital: '北京积水潭医院',
            specialty: '骨折、关节疾病、脊柱疾病',
            avatar: 'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=4444444444,4444444444&fm=26&gp=0.jpg',
            isOnline: true,
            consultationCount: 1024,
            rating: 97,
            price: 55
          }
        ],
        pediatric: [
          {
            id: 5,
            name: '陈医生',
            title: '副主任医师',
            hospital: '首都儿科研究所',
            specialty: '小儿感冒、发热、消化不良',
            avatar: 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=5555555555,5555555555&fm=26&gp=0.jpg',
            isOnline: true,
            consultationCount: 1456,
            rating: 98,
            price: 45
          }
        ],
        infectious: [
          {
            id: 6,
            name: '刘医生',
            title: '主任医师',
            hospital: '北京地坛医院',
            specialty: '传染病防控、肝炎、结核病',
            avatar: 'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=6666666666,6666666666&fm=26&gp=0.jpg',
            isOnline: false,
            consultationCount: 678,
            rating: 95,
            price: 50
          }
        ],
        dermatology: [
          {
            id: 7,
            name: '周医生',
            title: '主任医师',
            hospital: '北京大学人民医院',
            specialty: '皮肤过敏、湿疹、银屑病',
            avatar: 'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=7777777777,7777777777&fm=26&gp=0.jpg',
            isOnline: true,
            consultationCount: 934,
            rating: 96,
            price: 48
          }
        ],
        ent: [
          {
            id: 8,
            name: '吴医生',
            title: '副主任医师',
            hospital: '北京友谊医院',
            specialty: '鼻炎、咽炎、中耳炎',
            avatar: 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=8888888888,8888888888&fm=26&gp=0.jpg',
            isOnline: true,
            consultationCount: 567,
            rating: 94,
            price: 42
          }
        ],
        psychiatry: [
          {
            id: 9,
            name: '郑医生',
            title: '主任医师',
            hospital: '北京安定医院',
            specialty: '抑郁症、焦虑症、失眠',
            avatar: 'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=9999999999,9999999999&fm=26&gp=0.jpg',
            isOnline: false,
            consultationCount: 789,
            rating: 97,
            price: 65
          }
        ]
      }
    }
  },
  computed: {
    currentDoctors() {
      if (this.deptId) return this.doctorsList
      return this.doctorsData[this.activeDepartment] || []
    },
    // 根据排序项返回排序后的列表
    sortedDoctors() {
      const list = [...this.currentDoctors]
      if (this.sortKey === 'praise') {
        return list.sort((a, b) => (b.rating || 0) - (a.rating || 0))
      }
      if (this.sortKey === 'service') {
        return list.sort((a, b) => (b.consultationCount || 0) - (a.consultationCount || 0))
      }
      if (this.sortKey === 'price') {
        const factor = this.sortOrder === 'asc' ? 1 : -1
        return list.sort((a, b) => factor * ((a.price || 0) - (b.price || 0)))
      }
      // 综合：保持原顺序（后端已按综合度返回即可）
      return list
    }
  },
  async onLoad(options) {
    await this.fetchDepartments()
    if (options && options.deptId) {
      // 由首页带入 deptId 的场景
      this.deptId = Number(options.deptId)
      this.departmentName = options.deptName ? decodeURIComponent(options.deptName) : this.departmentName
      // 使对应 tab 高亮
      const found = this.departments.find(d => d.id === this.deptId)
      if (found) this.activeDepartment = String(found.key)
      this.fetchDoctors()
    } else if (options && options.department) {
      // 老的按名称映射场景（保留兼容）
      this.activeDepartment = options.department
      const dept = this.departments.find(d => d.key === options.department)
      if (dept) {
        this.departmentName = dept.name
        this.deptId = dept.id
        this.fetchDoctors()
      } else {
        this.departmentName = '内科'
      }
    } else {
      // 默认选中第一个科室
      if (this.departments.length) {
        this.activeDepartment = String(this.departments[0].key)
        this.deptId = this.departments[0].id
        this.departmentName = this.departments[0].name
        this.fetchDoctors()
      }
    }
  },
  methods: {
    goBack() {
      const pages = getCurrentPages()
      if (pages.length > 1) {
        uni.navigateBack()
      } else {
        uni.reLaunch({
          url: '/pages/index/index'
        })
      }
    },
    switchDepartment(departmentKey) {
      // 点击顶部科室：切换并按 deptId 拉取医生列表
      this.activeDepartment = departmentKey
      const dept = this.departments.find(d => String(d.key) === String(departmentKey))
      if (dept) {
        this.departmentName = dept.name
        this.deptId = dept.id
        this.fetchDoctors()
      }
    },
    viewDoctorDetail(doctor) {
      if (!doctor || !doctor.id) return
      uni.navigateTo({
        url: `/pages/doctors/detail?doctorId=${doctor.id}`
      })
    },
    changeSort(key) {
      this.sortKey = key
      if (key !== 'price') this.sortOrder = 'desc'
    },
    togglePriceSort() {
      if (this.sortKey !== 'price') {
        this.sortKey = 'price'
        this.sortOrder = 'asc'
      } else {
        this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc'
      }
    },
    async fetchDoctors() {
      try {
        const res = await getDoctorsByDeptId(this.deptId)
        const list = Array.isArray(res) ? res : (res.data || [])
        this.doctorsList = (list || []).map(d => {
          const ratingNum = parseFloat(d.praiseRate)
          const priceNum = parseFloat(d.consultFee)
          const serviceNum = parseInt(d.serviceCount)
          const rawAvatar = d.doctorImage || d.avatar || d.headImg || d.avatarUrl
          const avatar = this.normalizeUrl(rawAvatar)
          return {
            id: d.id || d.doctorId || d.userId,
            name: d.doctorName || d.name || d.realName || '医生',
            title: d.roleName || d.title || d.jobTitle || '医师',
            hospital: d.hospitalName || d.hospital || '',
            // 头像：优先 DoctorVo.doctorImage，支持相对路径拼接 baseUrl
            avatar: avatar || '/static/images/profile.jpg',
            // 在线状态暂无法确认，默认 false，可后续后端补充
            isOnline: d.isOnline === true || d.online === true || false,
            // 服务人数
            consultationCount: Number.isNaN(serviceNum) ? (d.consultationCount || d.serviceNum || 0) : serviceNum,
            // 好评率（百分比）
            rating: Number.isNaN(ratingNum) ? (d.rating || 98) : Math.round(ratingNum),
            // 价格（元/次）
            price: Number.isNaN(priceNum) ? (d.price || d.consultPrice || 0) : priceNum,
            // 保留 specialty 字段，若后端无“擅长”字段，可显示为空或医院名
            specialty: d.specialty || d.goodAt || d.skilled || ''
          }
        })
      } catch (e) {
        console.error('加载医生列表失败', e)
        this.$modal && this.$modal.msg('获取医生列表失败')
      }
    },
    // 将后端返回的相对路径拼接为完整 URL
    normalizeUrl(url) {
      if (!url) return ''
      if (/^https?:\/\//i.test(url)) return url
      // 若以 / 开头，拼接 baseUrl
      if (url.startsWith('/')) return `${config.baseUrl}${url}`
      return url
    },
    async fetchDepartments() {
      try {
        const res = await getDepartmentList()
        const list = Array.isArray(res) ? res : (res.data || [])
        // 标准化：id + name + key（用于样式/高亮）
        this.departments = (list || []).map((d, idx) => ({
          id: d.id || d.deptId || idx,
          name: d.name || d.deptName || d.departmentName || `科室${idx+1}`,
          key: (d.key || d.code || d.deptCode || (d.id || d.deptId || idx)).toString()
        }))
      } catch (e) {
        console.error('加载科室标签失败', e)
        // 失败则保留本地静态标签，不中断流程
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.doctors-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
  
  .back-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .header-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
  }
  
  .placeholder {
    width: 60rpx;
  }
}

.department-tabs {
  display: flex;
  background-color: #fff;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
  overflow-x: auto;
  white-space: nowrap;
  
  .tab-item {
    flex-shrink: 0;
    padding: 15rpx 30rpx;
    margin: 0 10rpx;
    border-radius: 30rpx;
    background-color: #f8f8f8;
    
    &.active {
      background-color: #667eea;
      color: #fff;
    }
    
    text {
      font-size: 28rpx;
    }
  }
}

.doctors-list {
  padding: 20rpx;
}

.doctor-card {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 28rpx 30rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.08);
  
  .doctor-avatar {
    position: relative;
    width: 110rpx;
    height: 110rpx;
    margin-right: 20rpx;
    
    image {
      width: 100%;
      height: 100%;
      border-radius: 55rpx;
    }
    
    .online-status {
      position: absolute;
      bottom: 5rpx;
      right: 5rpx;
      width: 24rpx;
      height: 24rpx;
      border-radius: 12rpx;
      background-color: #ccc;
      border: 3rpx solid #fff;
      
      &.online {
        background-color: #52c41a;
      }
    }
  }
  
  .doctor-info {
    flex: 1;
    min-width: 0; /* 允许内部省略号 */
    padding-right: 16rpx; /* 与右侧按钮留白 */
    
    .doctor-name {
      font-size: 30rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 6rpx;
    }
    
    .doctor-meta {
      display: flex;
      align-items: center;
      gap: 8rpx;
      font-size: 24rpx;
      margin-bottom: 8rpx;
      overflow: hidden;
      .role { color: #667eea; }
      .divider { color: #bbb; }
      .hospital {
        color: #666;
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
    
    .doctor-specialty {
      font-size: 24rpx;
      color: #8c8c8c;
      line-height: 1.5;
      margin-bottom: 10rpx;
    }
    
    .doctor-stats {
      display: flex;
      gap: 24rpx;
      
      .consultation-count,
      .rating {
        font-size: 22rpx;
        color: #9aa0a6;
      }
    }
  }
  
  .consultation-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 160rpx;
    height: 96rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 14rpx;
    
    .btn-text {
      font-size: 24rpx;
      color: #fff;
      margin-bottom: 6rpx;
    }
    
    .price {
      font-size: 22rpx;
      color: #fff;
      opacity: 0.95;
    }
  }
}
</style>